package com.shaozi.nc.manage.observer;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.shaozi.data.mq.business.base.SourceTypeConsts.OA.Attendance;
import com.shaozi.data.mq.business.observer.MqTargetObserverBean;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.hibVO.AttendanceLevelVO;
import com.shaozi.nc.hibservice.AttendanceLevelService;
import com.shaozi.nc.manage.observer.base.BaseSecretaryObserver;
import com.shaozi.nc.mq.bean.attendance.CommonBean;
import com.shaozi.nc.quartz.manage.AttendanceSignRuleManage;

/**
 * 考勤观察者 设置 已经读 ：https://shimo.im/doc/BESz6u08M9Ap3Ju7
 * 
 * @author lyx
 *
 */
public class AttendanceObserver extends BaseSecretaryObserver implements Observer {

	private Logger logger = Logger.getLogger(AttendanceObserver.class);

	@Autowired
	private AttendanceLevelService attendanceLevelService;
	@Autowired
	private AttendanceSignRuleManage attendanceSignRuleManage;

	// 提交考勤 8001,8002
	private static final Integer[] Notice_sourceType = { Attendance.Punch_In, Attendance.Punch_Out };

	@Override
	public void update(Observable o, Object arg) {
		if (arg != null) {
			if (arg instanceof MqTargetObserverBean) {
				MqTargetObserverBean mqBean = (MqTargetObserverBean) arg;
				int sourceType = mqBean.getSourceType();
				switch (sourceType) {
				// 考情规则变更 时时发送
				case Attendance.Rule_Update:
					if (mqBean.getBiz() instanceof CommonBean) {
						CommonBean obj = (CommonBean) mqBean.getBiz();
						if (obj != null) {
							try {
								updateRule2Job(mqBean, obj);
							} catch (Exception e) {
								logger.error(e);
							}
						}
					}
					break;
				case Attendance.Notices:// 提交考勤
				case Attendance.Notice:// 提交考勤
					updateUserRead(sourceType, mqBean, Notice_sourceType);
					break;
				default:
					break;
				}
			}
		}
	}

	private void updateRule2Job(MqTargetObserverBean mqBean, CommonBean obj) throws SzException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException, SchedulerException {
		Integer ruleId = obj.getRuleId();
		if (ruleId == null) {
			logger.warn("8009 ruleId is null 无法修改定时任务");
			return;
		}

		String companyId = mqBean.getCompanyId();
		if (StringUtils.isEmpty(companyId)) {
			logger.warn("8009 companyId is null 无法修改定时任务");
			return;
		}
		List<AttendanceLevelVO> levelVOs = attendanceLevelService.loadList(ruleId);
		attendanceSignRuleManage.scheduleByAttendanceLevelAndObserver(levelVOs, companyId);
	}

}
